<template>
  <div class="search-modal">
    <el-popover
      ref="popover"
      popper-class="el-popper-search"
      :placement="placement"
      :disabled="disabled"
      v-model="isVisibleTable"
      :trigger="trigger"
    >
      <el-input
        class="el-input-table"
        :placeholder="placeholder"
        @focus="inputFocusHandler"
        :disabled="disabled"
        clearable
        slot="reference"
        v-model="defaultValue"
      >
        <i
          style="cursor: pointer"
          slot="suffix"
          :class="{ 'el-icon-arrow-up': true, 'el-select__caret': true, 'is-reverse': isVisibleTable }"
        ></i>
      </el-input>
      <div class="container" :class="className" :style="{ width: width }">
        <template v-if="isCollect">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="搜索列表" name="first">
              <SearchList
                :tableData="tableData"
                :tableFields="computedTableFields"
                v-bind="$attrs"
                v-on="$listeners"
                @keyEnter="keyEnterHandler"
                @change="changeHandler"
                @loveHandler="loveHandler"
                @changePage="onChangePageHandler"
              />
            </el-tab-pane>
            <el-tab-pane label="收藏" name="second">
              <CollectHistory
                :collectHistoryList="collectHistoryList"
                :tableData="tableData"
                :tableFields="computedTableFields"
                v-bind="$attrs"
                v-on="$listeners"
                @keyEnter="keyEnterHandler"
                @change="changeHandler"
                @cancelLoveHandler="cancelLoveHandler"
                @changePage="onChangePageHandler"
              />
            </el-tab-pane>
          </el-tabs>
        </template>
        <template v-else>
          <SearchList
            :tableData="tableData"
            :tableFields="computedTableFields"
            :isCollect="isCollect"
            v-bind="$attrs"
            v-on="$listeners"
            @keyEnter="keyEnterHandler"
            @change="changeHandler"
            @changePage="onChangePageHandler"
          />
        </template>
      </div>
    </el-popover>
  </div>
</template>
<script>
import SearchList from './SearchList';
import CollectHistory from './CollectHistory';
/********************************定义一个方法将mixins中的文件全部导入进来 start********************************/
const mixinsList = [];
function importAll(r) {
  r.keys().forEach((key) => mixinsList.push(r(key).default));
}
importAll(require.context('./mixins', true, /\.js/));
/********************************定义一个方法将mixins中的文件全部导入进来 end********************************/

export default {
  name: 'SiruiTable',
  mixins: mixinsList,
  props: {
    width: {
      type: String,
      default: () => '800px',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },

    placement: {
      type: String,
      default: () => 'top',
    },
    //默认值
    value: {
      type: String,
      default: () => '',
    },
    // 点击方式
    trigger: {
      type: String,
      default: () => 'click',
    },
    className: {
      type: String,
      default: '',
    },
    isCollect: {
      type: Boolean,
      default: true,
    },
    // 根据搜索类型来显示不同的表格
    searchType: {
      type: String,
      default: '',
      required: true,
    },
    // 搜索额外参数
    extraData: {
      type: Object,
      default: () => {},
    },
    inputField: {
      type: String,
      default: 'id',
    },
  },
  data() {
    return {
      isVisibleTable: false,
      icon: 'el-icon-arrow-down',
      defaultValue: this.value,
      activeName: 'first',
      // 选择行列表
      selectRowList: [],
      // 收藏历史记录
      collectHistoryList: [],
      // 表格数据
      tableData: [
        {
          id: 1,
          date: '2016-05-03',
          name: 'Tom1',
          address: 'No. 189, Grove St, Los Angeles',
          age: 20,
        },
        {
          id: 2,
          date: '2016-05-02',
          name: 'Tom2',
          address: 'No. 189, Grove St, Los Angeles',
          age: 30,
        },
        {
          id: 3,
          date: '2016-05-04',
          name: 'Tom3',
          address: 'No. 189, Grove St, Los Angeles',
          age: 40,
        },
        {
          id: 4,
          date: '2016-05-01',
          name: 'Tom4',
          address: 'No. 189, Grove St, Los Angeles',
          age: 50,
        },
      ],
      pageSize: 10,
      pageNumber: 1,
    };
  },
  computed: {
    // 根据类型来选择表格字段
    computedTableFields() {
      return this[`${this.searchType}TableFields`];
    },
  },
  methods: {
    inputFocusHandler() {
      if (this.trigger !== 'click') {
        this.isVisibleTable = true;
      }
      if (this.initShow) this.getData();
      this.icon = 'el-icon-arrow-up';
    },
    inputBlurHandler() {
      this.isVisibleTable = false;
    },
    handleClick(e) {
      this.activeName = e.name;
    },
    // 键盘回车事件
    keyEnterHandler(selectRowList) {
      console.log(selectRowList, '选中的数据');
      this.inputBlurHandler();
      this.selectRowList = selectRowList;
    },
    changeHandler(selectRowList) {
      this.selectRowList = selectRowList;
    },
    // 收藏
    loveHandler(rowItem) {
      this.tableData = this.tableData.map((item) => {
        if (item.id == rowItem.id) {
          return {
            ...item,
            love: !!!item.love,
          };
        } else {
          return item;
        }
      });
      // 处理收藏记录
      const collectHistoryList = this.tableData.filter((item) => item.love);
      this.collectHistoryList = collectHistoryList;
      // TODO 调用后端接口
    },
    // 取消收藏
    cancelLoveHandler(rowItem) {
      const collectHistoryList = this.collectHistoryList.filter((item) => item.id != rowItem.id);
      console.log(collectHistoryList, '取消收藏');
      this.collectHistoryList = collectHistoryList;
      if (collectHistoryList && Array.isArray(collectHistoryList) && collectHistoryList.length) {
        const idList = collectHistoryList.map((item) => item.id);
        this.tableData = this.tableData.map((item) => {
          if (!idList.includes(item.id)) {
            return {
              ...item,
              love: false,
            };
          } else {
            return item;
          }
        });
      } else {
        this.tableData = this.tableData.map((item) => {
          return {
            ...item,
            love: false,
          };
        });
      }
      // TODO 调用后端接口
    },
    // 分页操作
    onChangePageHandler({ pageNumber, pageSize }) {
      this.pageNumber = pageNumber;
      this.pageSize = pageSize;
      this[`${this.searchType}QueryTableData`](this.value, pageNumber, pageSize, this.extraData);
    },
  },
  watch: {
    isVisibleTable(value) {
      if (value) {
        this.icon = 'el-icon-arrow-up';
      } else {
        this.icon = 'el-icon-arrow-down';
        this.defaultValue = this.selectRowList.map((item) => item[this.inputField]).join(',');
        this.$emit('input', this.selectRowList);
      }
    },
    defaultValue: {
      handler(val) {
        // TODO 处理限流操作
        this[`${this.searchType}QueryTableData`](val, this.pageNumber, this.pageSize, this.extraData);
      },
    },
  },
  components: {
    SearchList,
    CollectHistory,
  },
};
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
